package com.collectplus.express;

import java.lang.reflect.ParameterizedType;

import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.widget.TextView;

import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;

import droid.frame.activity.title.TitleRes;

/**
 * ProgressBar内嵌到layout内<br>
 * 采用模板设计模式, 整个流程(执行顺序)如下<br>
 * {@link #onCreate(android.os.Bundle)} {@link #findViewById()} {@link #onLoadStart()} {@link #handleMessage(Message)} {@link #onLoadComplete(AppResult)}
 * 
 * @author coffee<br>
 *         2017-1-4下午12:36:59
 */
public abstract class BaseActivityWithLoading<T> extends BaseActivity2 {

	/**
	 * 加载完成以后显示的layout
	 */
	private int layout;

	/**
	 * 进度条文本
	 */
	private TextView mLoadingText;
	/**
	 * 加载失败以后的提示
	 */
	private TextView mFaildTip;

	/**
	 * 重写父类, 该方法的主要作用是: 初始化View数据, 加载http
	 */
	@Override
	protected void findViewById() {
		super.setContentView(R.layout.app_onload);
		if (getAppTitle() == null) {
			super.findViewById();
			mLoadingText = (TextView) findViewById(R.id.app_loading_message);
			mFaildTip = (TextView) findViewById(R.id.app_faild_tip);
		}
		if (mSwipeLayout != null) {
			super.mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {
				@Override
				public void onRefresh() {
					findViewById();
				}
			});
		}
	}

	/**
	 * 数据加载完成<br>
	 * 把之前的TitleRes设置到新的layout上
	 * 
	 * @param <T>
	 */
	protected void onLoadComplete(AppResult<T> result) {
		TitleRes[] reses = getAppTitle().getTitlereReses();
		super.setContentView(layout);
		super.findViewById();
		getAppTitle().setTitle(reses);
	}

	/**
	 * 重写父类的方法, 不加载layout, 仅仅记录load data之后要显示的layout
	 */
	@Override
	public void setContentView(int layout) {
		this.layout = layout;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		Class<T> tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		final AppResult<T> result = JSON.parser(msg.obj, tClass);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (result.isSuccess()) {
					onLoadComplete(result);
				} else {
					findViewById(R.id.app_loading_layout).setVisibility(View.GONE);
					findViewById(R.id.app_faild_layout).setVisibility(View.VISIBLE);
					mFaildTip.setText(result.getMessage());
				}
			}
		});
		return true;
	}

	/**
	 * 重写父类的加载进度条
	 */
	@Override
	public void showLoadingDialog(String dialogMessage) {
		if (isEmpty(dialogMessage)) {
			mLoadingText.setVisibility(View.GONE);
		} else {
			mLoadingText.setVisibility(View.VISIBLE);
			mLoadingText.setText(dialogMessage);
		}
	}
}
